import React, { useState } from 'react';
import {
  IconButton, Menu, MenuItem, ListItemIcon, Divider
} from '@mui/material';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import Logout from '@mui/icons-material/Logout';
import Settings from '@mui/icons-material/Settings';
import { useNavigate } from 'react-router-dom';


interface Props {
  onNavigate: (page: string) => void;
}

const AccountMenu: React.FC<Props> = ({ onNavigate }) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const navigate = useNavigate();
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  /**only used to clear some resources */
  const handleClose = () => {
    
    setAnchorEl(null);
  };

  const handleLogout = () => {
    console.log("Logging out...");
    localStorage.removeItem("token")
    handleClose();
    window.location.href = "/login";
    // 可扩展为清除登录态并跳转登录页
  };

  const handleUserSettings = () => {
    handleClose();
    navigate('/userManage')
  };

  return (
    <>
      <IconButton
        onClick={handleMenuOpen}
        color="inherit"
        size="large"
        sx={{ ml: 1 }}
      >
        <AccountCircleIcon />
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        PaperProps={{
          sx: {
            mt: 1.5,
            minWidth: 160,
            bgcolor: "#1E2A4B",
            color: "#fff",
            border: "1px solid #3C5A99",
          },
        }}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
      >
        <MenuItem onClick={handleUserSettings}>
          <ListItemIcon>
            <Settings sx={{ color: '#8AB4F8' }} fontSize="small" />
          </ListItemIcon>
          用户设置
        </MenuItem>

        <Divider sx={{ borderColor: "#3C5A99" }} />

        <MenuItem onClick={handleLogout}>
          <ListItemIcon>
            <Logout sx={{ color: '#FF6B6B' }} fontSize="small" />
          </ListItemIcon>
          登出
        </MenuItem>
      </Menu>
    </>
  );
};

export default AccountMenu;
